//
//  SalesAfterListVC.m
//  sensen_ios
//
//  Created by mc on 16/2/26.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "SalesAfterListVC.h"

#import "OrderProductCell.h"

#import "OrderModel.h"
#import "CartProductModel.h"

#import "OrderProductDetailVC.h"


@interface SalesAfterListVC ()<UITableViewDataSource, UITableViewDelegate>{
    NSInteger _curpage;//页码,默认0
    NSInteger _pageSize;//每页显示个数，默认10,最大30,最小1,
    NSInteger _status;
}

@property (nonatomic, strong) UITableView *tableView; // 表视图
@property (nonatomic, strong) UIView * emptyView;
@property (nonatomic, strong) NSMutableArray *dataArray;
// 一些小的子视图要用到，设为全局
//@property (nonatomic, strong) UIImageView *remindView; // 有消息时候提醒，因为关乎是否隐藏，故设为全局

@end

@implementation SalesAfterListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self _initTableView];
    
    self.title = @"退款／售后";
    
    // 创建导航栏左边返回按钮
    [self createLeftBarButtonItemWithImagename:nil];
    //[self createRightBarButtonItemsWithImagenameAry:@[@"下拉菜单按钮"]];
    
    
    [self _getData];
    // 下拉加载更多
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(_getData)];
    _tableView.header = header;

    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    // 设置导航栏颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main hideTabBar];
}




//#pragma mark - 创建视图
//// 右侧按钮的样式可以自定义，由imgname控制，如果是文字则调用下面的接口
//- (void)createRightBarButtonItemsWithImagenameAry:(NSArray *)imgnameAry {
//    NSMutableArray *itemsAry = [[NSMutableArray alloc] init];
//    for (int i = 0; i < imgnameAry.count; i ++) {
//        
//        UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
//        customView.userInteractionEnabled = YES;
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightClick:)];
//        [customView addGestureRecognizer:tap];
//        
//        // 图标
//        UIImageView *rightButton = [[UIImageView alloc] initWithFrame:CGRectMake((customView.width - 6)/2.0, 3, 6, 24)];
//        rightButton.userInteractionEnabled = YES;
//        [rightButton setImage:[UIImage imageNamed:imgnameAry[i]]];
//        [customView addSubview:rightButton];
//        
//        // 有消息时候的蓝点
//        _remindView = [[UIImageView alloc] initWithFrame:CGRectMake(rightButton.right + 3, rightButton.top - 2, 8, 8)];
//        _remindView.userInteractionEnabled = YES;
//        _remindView.image = [UIImage imageNamed:@"下拉菜单消息提示"];
//        [customView addSubview:_remindView];
//        
//        UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:customView];
//        [itemsAry addObject:rightBarButton];
//    }
//    self.navigationItem.rightBarButtonItems = itemsAry;
//}
//



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 创建表视图
- (void)_initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT  - 64) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [self _initNoDataView];
    [self _noHiddenTableView];
    // 下拉加载更多
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(_getMoreData)];
    _tableView.footer = footer;

}


//当没有数据时，隐藏表视图，显示没有数据图
- (void)_hiddenTableView{
    _tableView.hidden = YES;
    _emptyView.hidden = NO;
}

//当有数据时，显示表视图，隐藏没有数据图
- (void)_noHiddenTableView{
    _tableView.hidden = NO;
    _emptyView.hidden = YES;
}

// 创建没有订单视图
- (void)_initNoDataView{
    _emptyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT  - 64)];
    _emptyView.backgroundColor = rgba(237, 238, 239, 1);
    [self.view addSubview:_emptyView];
    UIImageView * imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:@"我的订单_没有数据"];
    [_emptyView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_emptyView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(80, 80));
        make.top.equalTo(_emptyView.mas_top).offset(SCREEN_HEIGHT / 4);
    }];
    
    
    UILabel * Label = [[UILabel alloc] init];
    [_emptyView addSubview:Label];
    [Label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_emptyView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(180, 25));
        make.top.equalTo(imageView.mas_bottom).offset(20);
    }];
    Label.text = @"您还没有相关订单";
    Label.textColor = SS_NAVI_ORANGE_COLOR;
    Label.textAlignment = NSTextAlignmentCenter;
    Label.font = [UIFont systemFontOfSize:15];
    
}


- (void)_getData {
    [SVProgressHUD showWithStatus:@"正在加载..."]; // 请求中
    _pageSize = 10;
    _curpage = 0;
    
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:1];
    UserModel *user = [CommonCache getUserInfo];
    [diction setObject:user.uid forKey:@"uid"];
    NSLog(@"uid = %@", user.uid);
    [diction setObject:@"5" forKey:@"status"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_curpage] forKey:@"curpage"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_pageSize] forKey:@"pageSize"];
    __weak typeof (self) weakSelf = self;
    [BoyeHttpClient post:@"BY_Orders_query" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        
        NSLog(@"退款与售后 ＝ %@", result);
        
        if (_dataArray == nil) {
            _dataArray = [[NSMutableArray alloc] init];
        } else {
            [_dataArray removeAllObjects];
        }

        if ([result isKindOfClass:[NSString class]]) {
            if ([result isEqualToString:@""]) {
                [weakSelf _hiddenTableView];
            }
        }else{
            if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
                NSDictionary *diction = result[@"list"];
                NSArray * keys = diction.allKeys;
                for (NSString * key in keys) {
                    NSDictionary * dic = [diction objectForKey:key];
                    OrderModel * model = [[OrderModel alloc] initContentWithDic:dic];
                    model.order_id = dic[@"id"];
                    model._items = [NSMutableArray array];
                    NSMutableArray * items = dic[@"_items"];
                    for (int i = 0; i < items.count; i++) {
                        NSDictionary *itemsDic = [items objectAtIndex:i];
                        CartProductModel *item = [[CartProductModel alloc] initContentWithDic:itemsDic];
                        [model._items addObject:item];
                    }
                    [weakSelf.dataArray addObject:model];
                }
                NSLog(@"售后个数  %ld", (unsigned long)weakSelf.dataArray.count);
            }
            
        }
        [SVProgressHUD dismiss];
        [_tableView.header endRefreshing]; // 结束刷新
        weakSelf.dataArray = [weakSelf ArraySort:weakSelf.dataArray];
        [weakSelf.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_tableView.header endRefreshing]; // 结束刷新
        [SVProgressHUD showErrorWithStatus:@"请求失败" withDuration:2];
    }];
    
    
}


- (void)_getMoreData {
    [SVProgressHUD showWithStatus:@"请求中..."]; // 请求中
    _pageSize += 1;
    _curpage = 10;
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:1];
    UserModel *user = [CommonCache getUserInfo];
    [diction setObject:user.uid forKey:@"uid"];
    [diction setObject:@"5" forKey:@"status"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_curpage] forKey:@"curpage"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_pageSize] forKey:@"pageSize"];
    
    __weak typeof (self) weakSelf = self;
    [BoyeHttpClient post:@"BY_Orders_query" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"加载更多中  %@", result);
        if ([result isKindOfClass:[NSString class]]) {
            if ([result isEqualToString:@""]) {
                [_tableView.footer endRefreshing];
                
            }
        }else{
            if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
                NSDictionary *diction = result[@"list"];
                NSArray * keys = diction.allKeys;
                for (NSString * key in keys) {
                    NSDictionary * dic = [diction objectForKey:key];
                    OrderModel * model = [[OrderModel alloc] initContentWithDic:dic];
                    model.order_id = dic[@"id"];
                    model._items = [NSMutableArray array];
                    NSMutableArray * items = dic[@"_items"];
                    for (int i = 0; i < items.count; i++) {
                        NSDictionary *itemsDic = [items objectAtIndex:i];
                        CartProductModel *item = [[CartProductModel alloc] initContentWithDic:itemsDic];
                        [model._items addObject:item];
                    }
                    
                    [weakSelf.dataArray addObject:model];
                }
            }
            
        }
        
        [SVProgressHUD dismiss];
        [_tableView.footer endRefreshing];
        weakSelf.dataArray = [weakSelf ArraySort:weakSelf.dataArray];
        [weakSelf.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_tableView.footer endRefreshing];
        [SVProgressHUD showErrorWithStatus:@"请求失败" withDuration:2];
    }];
    
    
}

//排序
-(NSMutableArray *)ArraySort:(NSMutableArray *)list{
    if (list.count == 0 || list.count == 1) {
        return list;
    }
    
    int i,j;
    //两重for循环对数组进行比较和交换
    for(i = 0;i < list.count - 1;i++)
    {
        for(j = i+1;j < list.count;j++){
            OrderModel * model1 = [list objectAtIndex:i];
            OrderModel * model2 = [list objectAtIndex:j];
            
            if([model1.updatetime longLongValue] < [model2.updatetime longLongValue]){
                [list exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
        }
    }
    return list;
}


#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    OrderModel * model = [self.dataArray objectAtIndex:section];
    return model._items.count + 2;
}

// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     OrderModel * model = [self.dataArray objectAtIndex:indexPath.section];
    
    NSLog(@"付款类型 ＝ %@ 订单类型 ＝ %@ 售后状态 ＝ %@", model.pay_status, model.order_status, model.cs_status);
    
    
    if (indexPath.row >0 && indexPath.row < model._items.count + 1) {
        CartProductModel * item = [model._items objectAtIndex:indexPath.row - 1];
        OrderProductCell *cell = [OrderProductCell cellWithTableView:tableView];
        [cell.ivContent setImageURLStr:item.img_url placeholder:DEFAULT_IMAGE];
        cell.lblTitle.text = item.name;
        cell.lblBrand.text = item.sku_desc;
        cell.lblPrice.text = [NSString stringWithFormat:@"¥%@", item.price];
        cell.lblCount.text = [NSString stringWithFormat:@"X %@", item.count];
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else if (indexPath.row == 0){
        static NSString * cellIdentifier = @"Cell1";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell ==nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        
        for (UIView *view in cell.subviews) {
            [view removeFromSuperview];
        }
        UILabel * lable = [[UILabel alloc] init];
        lable.textAlignment = NSTextAlignmentCenter;
        lable.textAlignment = NSTextAlignmentRight;
        [cell addSubview:lable];
        [lable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.mas_top).offset(0);
            make.bottom.equalTo(cell.mas_bottom).offset(0);
            make.right.equalTo(cell.mas_right).offset(-10);
            make.left.equalTo(cell.mas_left).offset(0);
        }];
        lable.textColor = [UIColor darkGrayColor];
        lable.font = [UIFont systemFontOfSize:13];
        lable.text = @"卖家处理中";
        lable.textColor = [UIColor redColor];
        if ([model.cs_status integerValue] == 2){
            lable.text = @"等待卖家处理";
        }else if ([model.cs_status integerValue] == 3){
             lable.text = @"售后完成";
        }
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
        
    }else{
        static NSString * cellIdentifier = @"Cell2";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell ==nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        
        
        for (UIView *view in cell.subviews) {
            [view removeFromSuperview];
        }
        UILabel * lable = [[UILabel alloc] init];
        lable.textAlignment = NSTextAlignmentCenter;
        lable.textAlignment = NSTextAlignmentRight;
        [cell addSubview:lable];
        [lable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.mas_top).offset(0);
            make.bottom.equalTo(cell.mas_bottom).offset(-0.5);
            make.right.equalTo(cell.mas_right).offset(-10);
            make.left.equalTo(cell.mas_left).offset(10);
        }];
        lable.textColor = [UIColor darkGrayColor];
        lable.font = [UIFont systemFontOfSize:13];
        
        NSInteger count = 0;
        for (CartProductModel * temp in model._items) {
            count += [temp.count integerValue];
        }
        
        int discount_money  = [model.discount_money intValue];
        if (discount_money > 0) {
            lable.text = [NSString stringWithFormat:@"共%ld件商品 合计:¥%@(优惠¥%@，含运费¥%@)", (long)count, model.price, model.discount_money, model.post_price];
        }else{
             lable.text = [NSString stringWithFormat:@"共%ld件商品 合计:¥%@(含运费¥%@)", (long)count, model.price, model.post_price];
        }
        lable.adjustsFontSizeToFitWidth = YES;
       

        //加条线
        UILabel * lable2 = [[UILabel alloc] init];
        [cell addSubview:lable2];
        [lable2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell).offset(0);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 0.5));
            make.bottom.equalTo(cell).offset(-0.5);
        }];
        lable2.backgroundColor = [UIColor lightGrayColor];
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;

    }
}


// 设置单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    OrderModel * model = [self.dataArray objectAtIndex:indexPath.section];
    
    if (indexPath.row > 0 && indexPath.row < model._items.count + 1) {
        return 75;
    }else if (indexPath.row == 0){
        return 30;
    }else{
        return 30;
    }
    
}
// 设置组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == self.dataArray.count - 1) {
        return 5;
    }else{
        return 10;
    }
    
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == self.dataArray.count - 1) {
        return nil;
    }else{
        UIView * view = [[UIView alloc] init];
        view.backgroundColor = [BoyeTool colorFromHexRGB:@"#f5f5f5"];
        return view;

    }
}



// 设置组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

//- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//   
//        UIView * view = [[UIView alloc] init];
//        view.backgroundColor = [UIColor whiteColor];
//        return view;
//        
//
//}






- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];// 取消选中阴影
    OrderModel * model = [self.dataArray objectAtIndex:indexPath.section];
    OrderProductDetailVC *vc = [[OrderProductDetailVC alloc] init];
    vc.order_id = model.order_id;
    vc.order_code = model.order_code;
    if ([model.cs_status integerValue] == 2){
        [SVProgressHUD showOnlyStatus:@"售后中的订单不能查看详情" withDuration:1];
    }else{
        [self.navigationController pushViewController:vc animated:YES];
    }
    

}



#pragma mark 分割线距离左边距离
-(void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
